<?php
    /**
    * getPostViews()函数
    * 功能：获取阅读数量
    * 在需要显示浏览次数的位置，调用此函数
    * @Param object|int $postID   文章的id
    * @Return string $count		  文章阅读数量
    */
    function getPostViews( $postID ) {
        $count_key = 'post_views_count';
        $count = get_post_meta( $postID, $count_key, true );
        if( $count=='' ) {
            delete_post_meta( $postID, $count_key );
            add_post_meta( $postID, $count_key, '0' );
            return "0";
        }
    return $count;
    }


    /**
    * setPostViews()函数  
    * 功能：设置或更新阅读数量
    * 在内容页(single.php，或page.php )调用此函数
    * @Param object|int $postID   文章的id
    * @Return string $count		  文章阅读数量
    */
    function setPostViews( $postID ) {
        $count_key = 'post_views_count';
        $count = get_post_meta( $postID, $count_key, true );
        if( $count=='' ) {
            $count = 0;
            delete_post_meta( $postID, $count_key );
            add_post_meta( $postID, $count_key, '0' );
        } else {
            $count++;
            update_post_meta( $postID, $count_key, $count );
        }
    }
    /*
    register_sidebar( $args )
    函数功能：开启侧边栏功能
    @参数 array $args，参数是一个数组，包含多个成员参数。
    所有可选的成员参数，都包含在下面的示例代码中。
    */
    register_sidebar( array(
        'name'						=> '主侧边栏',					//侧边栏的名称
        'id'								=> 'sidebar-1',					//侧边栏的编号
        'description'				=> '用于网站右侧的主侧边栏',					//侧边栏的描述
        'class'						=> '',
        'before_widget'			=> '<li id="%1$s" class="widget %2$s">',
        'after_widget'			=> '</li>',
        'before_title'				=> '<h3 class="widget-title">',
        'after_title'					=> '</h3>' 
    ) );
    /**格式化站点title */
    add_filter('wp_title','yw_wp_head',10,3);
    function yw_wp_head($title,$sep,$seplocation ){
        global $paged,$page;
        if(is_feed()){
            return $title;
        }

        $title.=get_bloginfo('name').'-'; //获取站点名称
        $title.=get_bloginfo('description','display');

        if($paged>=2 || $page>=2){
            $title.=printf('第%s页',max($paged,$page));
        }

        $search = array('&#8211;', ' '); //去除空格，-的字符实体
        $replace = array('-', '');
        $title = str_replace($search, $replace, $title);
        return $title;
    }

    /**添加功能 */

    add_theme_support('post-thumbnails'); //缩略图功能

    add_theme_support('automatic-feed-links'); //添加feed功能

    add_action('after_setup_theme','yw_set_up');
    function yw_set_up(){ 
        add_theme_support('custom-logo',[ //开启自定义logo功能
            'height'=>250,
            'weight'=>250,
            'flex-weight'=>true,
            'flex-height'=>true,
        ]);
    }

    /**加载样式 js文件 */
    add_action('wp_enqueue_scripts','yw_enqueue_scriptions');
    function yw_enqueue_scriptions(){ //加载资源文件
        wp_enqueue_style('blog_style',get_stylesheet_uri()); //加载style.css 样式
        // wp_enqueue_script( '_s-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );
        //说明：参数1 唯一标识。参数2 文件地址 参数3 所依赖的脚本 参数4 当前脚本版本号 参数5 是否默认在 </body>前加载脚本
        wp_enqueue_script( 'blog_jquery', get_template_directory_uri() . '/js/jquery.min.js', array(), '20151215', false );
        wp_enqueue_script( 'blog_bxSlider', get_template_directory_uri() . '/js/jquery.bxSlider.min.js', array('blog_jquery'), '20151215', true );
        wp_enqueue_script( 'blog_slide', get_template_directory_uri() . '/js/bxslider.js', array('blog_jquery'), '20151215', true );
    }

    /** 注册导航*/
    register_nav_menu('yw-main','主导航');
    register_nav_menu('yw-foot','底部导航');

    /**
    * lingfeng_breadcrumbs()函数
    * 功能是输出面包屑导航HTML代码
    * @Param null			不需要输入任何参数
    * @Return string		输出HTML代码
    */
    function lingfeng_breadcrumbs() {
        /* === OPTIONS === */
        $text['home']     = '网站首页'; // text for the 'Home' link
        $text['category'] = '%s'; // text for a category page
        $text['search']   = '"%s"的搜索结果'; // text for a search results page
        $text['tag']      = '%s'; // text for a tag page
        $text['author']   = '%s'; // text for an author page
        $text['404']      = '404错误'; // text for the 404 page

        $show_current   = 1; // 1 - show current post/page/category title in breadcrumbs, 0 - don't show
        $show_on_home   = 1; // 1 - show breadcrumbs on the homepage, 0 - don't show
        $show_home_link = 1; // 1 - show the 'Home' link, 0 - don't show
        $show_title     = 1; // 1 - show the title for the links, 0 - don't show
        $delimiter      = ' &raquo; '; // delimiter between crumbs
        $before         = '<span class="current">'; // tag before the current crumb
        $after          = '</span>'; // tag after the current crumb
        /* === END OF OPTIONS === */

        global $post;
        $home_link    = home_url('/');
        $link_before  = '<span typeof="v:Breadcrumb">';
        $link_after   = '</span>';
        $link_attr    = ' rel="v:url" property="v:title"';
        $link         = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
        $parent_id    = $parent_id_2 = $post->post_parent;
        $frontpage_id = get_option('page_on_front');

        if (is_home() || is_front_page()) {

            if ($show_on_home == 1) echo '<div class="breadcrumbs"><a href="' . $home_link . '">' . $text['home'] . '</a></div>';

        } else {

            echo '<div class="breadcrumbs" xmlns:v="http://rdf.data-vocabulary.org/#">';
            if ($show_home_link == 1) {
                echo '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $text['home'] . '</a>';
                if ($frontpage_id == 0 || $parent_id != $frontpage_id) echo $delimiter;
            }

            if ( is_category() ) {
                $this_cat = get_category(get_query_var('cat'), false);
                if ($this_cat->parent != 0) {
                    $cats = get_category_parents($this_cat->parent, TRUE, $delimiter);
                    if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats);
                    $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
                    $cats = str_replace('</a>', '</a>' . $link_after, $cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
                    echo $cats;
                }
                if ($show_current == 1) echo $before . sprintf($text['category'], single_cat_title('', false)) . $after;

            } elseif ( is_search() ) {
                echo $before . sprintf($text['search'], get_search_query()) . $after;

            } elseif ( is_day() ) {
                echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter;
                echo sprintf($link, get_month_link(get_the_time('Y'),get_the_time('m')), get_the_time('F')) . $delimiter;
                echo $before . get_the_time('d') . $after;

            } elseif ( is_month() ) {
                echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter;
                echo $before . get_the_time('F') . $after;

            } elseif ( is_year() ) {
                echo $before . get_the_time('Y') . $after;

            } elseif ( is_single() && !is_attachment() ) {
                if ( get_post_type() != 'post' ) {
                    $post_type = get_post_type_object(get_post_type());
                    $slug = $post_type->rewrite;
                    printf($link, $home_link . $slug['slug'] . '/', $post_type->labels->singular_name);
                    if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;
                } else {
                    $cat = get_the_category(); $cat = $cat[0];
                    $cats = get_category_parents($cat, TRUE, $delimiter);
                    if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats);
                    $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
                    $cats = str_replace('</a>', '</a>' . $link_after, $cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
                    echo $cats;
                    if ($show_current == 1) echo $before . get_the_title() . $after;
                }

            } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
                $post_type = get_post_type_object(get_post_type());
                echo $before . $post_type->labels->singular_name . $after;

            } elseif ( is_attachment() ) {
                $parent = get_post($parent_id);
                $cat = get_the_category($parent->ID); $cat = $cat[0];
                if ($cat) {
                    $cats = get_category_parents($cat, TRUE, $delimiter);
                    $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
                    $cats = str_replace('</a>', '</a>' . $link_after, $cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
                    echo $cats;
                }
                printf($link, get_permalink($parent), $parent->post_title);
                if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;

            } elseif ( is_page() && !$parent_id ) {
                if ($show_current == 1) echo $before . get_the_title() . $after;

            } elseif ( is_page() && $parent_id ) {
                if ($parent_id != $frontpage_id) {
                    $breadcrumbs = array();
                    while ($parent_id) {
                        $page = get_page($parent_id);
                        if ($parent_id != $frontpage_id) {
                            $breadcrumbs[] = sprintf($link, get_permalink($page->ID), get_the_title($page->ID));
                        }
                        $parent_id = $page->post_parent;
                    }
                    $breadcrumbs = array_reverse($breadcrumbs);
                    for ($i = 0; $i < count($breadcrumbs); $i++) {
                        echo $breadcrumbs[$i];
                        if ($i != count($breadcrumbs)-1) echo $delimiter;
                    }
                }
                if ($show_current == 1) {
                    if ($show_home_link == 1 || ($parent_id_2 != 0 && $parent_id_2 != $frontpage_id)) echo $delimiter;
                    echo $before . get_the_title() . $after;
                }

            } elseif ( is_tag() ) {
                echo $before . sprintf($text['tag'], single_tag_title('', false)) . $after;

            } elseif ( is_author() ) {
                global $author;
                $userdata = get_userdata($author);
                echo $before . sprintf($text['author'], $userdata->display_name) . $after;

            } elseif ( is_404() ) {
                echo $before . $text['404'] . $after;

            } elseif ( has_post_format() && !is_singular() ) {
                echo get_post_format_string( get_post_format() );
            }

            if ( get_query_var('paged') ) {
                if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
                echo __('Page') . ' ' . get_query_var('paged');
                if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
            }

            echo '</div><!-- .breadcrumbs -->';

        }
    } // end dimox_breadcrumbs()
    /**
    * lingfeng_strimwidth( ) 函数
    * 功能：字符串截取，并去除字符串中的html和php标签
    * @Param string $str			要截取的原始字符串
    * @Param int $len				截取的长度
    * @Param string $suffix		字符串结尾的标识
    * @Return string					处理后的字符串
    */
    function lingfeng_strimwidth( $str, $len, $start = 0, $suffix = '……' ) {
        $str = str_replace(array(' ', '　','&nbsp;', '\r\n'), '', strip_tags( $str ));
        if ( $len>mb_strlen( $str ) ) {
            return mb_substr( $str, $start, $len );
        }
        return mb_substr($str, $start, $len) . $suffix;
    }

    /**
    * 数字分页函数
    * 因为wordpress默认仅仅提供简单分页
    * 所以要实现数字分页，需要自定义函数
    * @Param int $range			数字分页的宽度
    * @Return string|empty		输出分页的HTML代码		
    */
    function lingfeng_pagenavi( $range = 4 ) {
        global $paged,$wp_query;
        if ( !$max_page ) {
            $max_page = $wp_query->max_num_pages;
        }
        if( $max_page >1 ) {
            echo "<div class='fenye'>"; 
            if( !$paged ){
                $paged = 1;
            }
            if( $paged != 1 ) {
                echo "<a href='".get_pagenum_link(1) ."' class='extend' title='跳转到首页'>首页</a>";
            }
            previous_posts_link('上一页');
            if ( $max_page >$range ) {
                if( $paged <$range ) {
                    for( $i = 1; $i <= ($range +1); $i++ ) {
                        echo "<a href='".get_pagenum_link($i) ."'";
                    if($i==$paged) echo " class='current'";echo ">$i</a>";
                    }
                }elseif($paged >= ($max_page -ceil(($range/2)))){
                    for($i = $max_page -$range;$i <= $max_page;$i++){
                        echo "<a href='".get_pagenum_link($i) ."'";
                        if($i==$paged)echo " class='current'";echo ">$i</a>";
                        }
                    }elseif($paged >= $range &&$paged <($max_page -ceil(($range/2)))){
                        for($i = ($paged -ceil($range/2));$i <= ($paged +ceil(($range/2)));$i++){
                            echo "<a href='".get_pagenum_link($i) ."'";if($i==$paged) echo " class='current'";echo ">$i</a>";
                        }
                    }
                }else{
                    for($i = 1;$i <= $max_page;$i++){
                        echo "<a href='".get_pagenum_link($i) ."'";
                        if($i==$paged)echo " class='current'";echo ">$i</a>";
                    }
                }
            next_posts_link('下一页');
            if($paged != $max_page){
                echo "<a href='".get_pagenum_link($max_page) ."' class='extend' title='跳转到最后一页'>尾页</a>";
            }
            echo '<span>共['.$max_page.']页</span>';
            echo "</div>\n";  
        }
    }


    //自定义评论列表模板
    function simple_comment($comment, $args, $depth) {
        $GLOBALS['comment'] = $comment; ?>
        <li class="comment" id="li-comment-<?php comment_ID(); ?>">
                <div class="media">
                    <div class="media-left">
                    <?php if (function_exists('get_avatar') && get_option('show_avatars')) { echo get_avatar($comment, 48); } ?>
                    </div>
                    <div class="media-body">
                        <?php printf(__('<p class="author_name">%s</p>'), get_comment_author_link()); ?>
                    <?php if ($comment->comment_approved == '0') : ?>
                        <em>评论等待审核...</em><br />
                    <?php endif; ?>
                    <?php comment_text(); ?>
                    </div>
                </div>
                <div class="comment-metadata">
                    <span class="comment-pub-time">
                        <?php echo get_comment_time('Y-m-d H:i'); ?>
                    </span>
                    <span class="comment-btn-reply">
                    <i class="fa fa-reply"></i> <?php comment_reply_link(array_merge( $args, array('reply_text' => '回复','depth' => $depth, 'max_depth' => $args['max_depth']))) ?> 
                    </span>
                </div>
    
    <?php
    }

/**
 * Adds Foo_Widget widget.
 */
class Foo_Widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	function __construct() {
		parent::__construct(
			'foo_widget', // Base ID
			esc_html__( 'Widget Title', 'text_domain' ), // Name
			array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args
		);
	}

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
        /**查询出浏览量高的文章*/
        $map=[
            'post_type'=>'post',
            'posts_per_page'=>10,
            'orderby'   => 'meta_value_num',
            'meta_key'  => 'post_views_count',
            'meta_value_num'  => 10,
            'meta_compare'  => '>=',
            'order'   => 'DESC',
        ];
        $my_query=new WP_Query($map);
        $out_html='';
        $out_html.='<li class="widget">';
        $out_html.='<h3>最受欢迎</h3>';
        $out_html.='<ul>';
        if($my_query->have_posts()){
            while($my_query->have_posts()){
                $my_query->the_post();
                $out_html.='<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
            }
        }else{
            $out_html.='<li>暂无内容</li>';
        }
        /* Restore original Post Data */
        wp_reset_postdata();
        $out_html.='</ul>';
        $out_html.='</li>';
        echo $out_html;
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
		?>
		<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label> 
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
		</p>
		<?php 
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';

		return $instance;
	}

} // class Foo_Widget

    add_action( 'widgets_init', function(){
        register_widget( 'Foo_Widget' );
    });